var http=require("http");

var fs=require("fs");

var path=require("path");

var filePath=fs.createWriteStream("./2.txt");



http.get("http://study.163.com/",function (res) {
    var getData="";
    var imgPath;
    res.on("data",function (data) {
        getData+=data;
    });
    res.on("end",function () {
        var imgPathReg=/src="(.*?[\.jpg|\.png|\.gif])"/img;
        while (imgPath=imgPathReg.exec(getData)){
            if(imgPath[1]){
                if(imgPath[1].indexOf(" ")>-1){
                    imgPath[1]=imgPath[1].substr(0,imgPath[1].indexOf(" "))
                }else{
                    imgPath[1]=imgPath[1];
                }
            }

            if(imgPath[1].substr(imgPath[1].length-3,imgPath[1].length-1)=="png"||imgPath[1].substr(imgPath[1].length-3,imgPath[1].length-1)=="jpg"){
                 // console.log(imgPath[1]);
                getUrl(imgPath[1]);
            }
        }

    })
});


function getUrl(imgPath) {
    // console.log(imgPath)

    if(imgPath.substr(0,4)=="http"){
        imgPath=imgPath
    }else{
        imgPath="http:"+imgPath;
    }
     var fName=path.parse(imgPath).base;
     var writePic=fs.createWriteStream("./files/"+fName);


     http.get(imgPath,function (res) {
         res.pipe(writePic);
         console.log(fName+"下载完成！");
     })


}

